package com.hefan.user.service;

import com.cat.common.constant.RedisKeyConstant;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ExpSourceEnum;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.GlobalConstants;
import com.cat.tiger.util.NumberUtils;
import com.hefan.common.exception.DataIllegalException;
import com.hefan.common.util.DateUtils;
import com.hefan.user.bean.UserLevelChangeVo;
import com.hefan.user.bean.WebUserWatch;
import com.hefan.user.bean.WebUserWatchDetail;
import com.hefan.user.config.UserConfigCenter;
import com.hefan.user.dao.WebUserWatchDao;
import com.hefan.user.itf.WebUserService;
import com.hefan.user.itf.WebUserWatchDayService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by hbchen on 2016/10/20.
 */
@Component("webUserWatchDayService")
public class WebUserWatchDayServiceImpl implements WebUserWatchDayService {

    Logger logger = LoggerFactory.getLogger(WebUserWatchDayServiceImpl.class);
    @Resource
    WebUserService webUserService;
    @Resource
    WebUserWatchDao webUserWatchDao;
    @Resource
    JedisService jedisService;
    @Resource
    private UserConfigCenter userConfigCenter;

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public void updateUserExpByWatchTime(String userId, long time) {

        double minutes = NumberUtils.divide(time , 60000) ;
        Map<String, String> user = userConfigCenter.getPublicConfig();
        //每次观看最大时间
        long maxWatchTime = StringUtils.isBlank(user.get("maxWatchTime")) ? 86400000L : Long.parseLong(user.get("maxWatchTime"));
        long seconds = time / 1000;
        //当用户提交观看时长大于最大值时，不更新
        if(time >maxWatchTime){
            logger.error("用户{}提交时长{}错误，不触发更新时长和经验", userId, time);
            throw new RuntimeException(String.format("用户%s提交时长%s错误，不触发更新时长和经验！", userId, time));
        }
        //算经验数
        double exp = minutes * GlobalConstants.EXP_WATCH_TIME_EXP;
        //按秒数加经验,不足30秒不加经验
        if (exp > 0 && seconds >= 30) {
            //更新天表的时长
            String currentDate = DateUtils.currentDate("yyyyMMdd");
            WebUserWatchDetail detail = new WebUserWatchDetail();
            detail.setUserId(userId);
            detail.setWatchDay(Integer.valueOf(currentDate));
            detail.setTotalTime(time);
            long totalTime = 0;
            //获取当前用户当天观看总时长
            try {
                String key = String.format(RedisKeyConstant.KEY_WATCH_TIME, currentDate, userId);
                totalTime = jedisService.incrBy2(key, time);
                jedisService.expire(key, GlobalConstants.LIVING_WATCH_NUM_CACHE_TIME);
                //如果总时长超过一天则不更新
                if(totalTime>86400000L){
                    totalTime = 0;
                }
            } catch (Exception e) {
                totalTime = 0;
                logger.error("redis查询用户{}观看时长异常", userId, e);
            }
            if (totalTime > 0) {
                //modify by 王超 20161628 观看时间每次insert web_user_watchday表，定时任务统计
                webUserWatchDao.saveWatchDetail(detail);
            }
            //            }
            //取总时长
            //long total_time = webUserWatchDao.queryWebUserWatchTime(userId,webUserWatch.getWatch_day());
            //如果总时长不大于3小时，增长经验
            if (totalTime > 0 && !ExpSourceEnum.checkIsLimit(ExpSourceEnum.WatchExp.getType(), totalTime)) {
                ResultBean<UserLevelChangeVo> resultBean = webUserService.userLevelOprate(userId, (long) exp);
                if (resultBean == null || resultBean.getCode() != ResultCode.SUCCESS.get_code()) {
                    throw new RuntimeException("等级更新异常！userId=" + userId);
                }
            }
        }

    }

    /**
     * 根据日期查询，所有用户观看时长
     *
     * @param time
     * @return
     * @throws
     * @description
     * @author wangchao
     * @create 2016/12/28 14:13
     */
    @Override
    public List<Map<String, Object>> getWatchTimeByDay(String time) {
        return webUserWatchDao.getWatchTimeByDay(time);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public void updateUserWatchTime(String userId, long watchTime, String time) throws Exception {
        WebUserWatch record = new WebUserWatch();
        record.setUserId(userId);
        record.setWatch_day(Integer.parseInt(time));
        record.setWatch_total_time(watchTime);
        int result = webUserWatchDao.queryWatchDayCount(record);
        if (result > 0) {
            webUserWatchDao.updateWebUserWatch(record);
        } else {
            webUserWatchDao.initWatchDay(record);
        }
        result = webUserService.updateUserWatchTime(userId, watchTime);
        if(result<=0){
            throw new DataIllegalException(String.format("保存web_user用户%s总时长%s错误", userId, watchTime));
        }
    }

}
